package com.shqcjd.yunweiyanoperator.ui.activity;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.orhanobut.logger.Logger;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.pojo.ShareBean;
import com.shqcjd.yunweiyanoperator.model.pojo.ShareVideoBean;
import com.shqcjd.yunweiyanoperator.ui.adapter.ShareAdapter;
import com.shqcjd.yunweiyanoperator.ui.adapter.ShareVideoListAdapter;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.Config;
import com.shqcjd.yunweiyanoperator.util.PrefUtils;
import com.shqcjd.yunweiyanoperator.util.SpacesItemDecoration;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.widget.AddTipDialog;
import com.shuyu.gsyvideoplayer.GSYVideoManager;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 企业管理-分享列表
 */
public class AdminShareActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener {
    List<ShareBean.ListBean> mList = new ArrayList<>();
    @BindView(R.id.rv_share)
    RecyclerView rvShare;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.btn_finish)
    ImageView btnFinish;
    @BindView(R.id.tv_title)
    TextView tvTitle;

    private Context mContext;
    private ShareAdapter shareAdapter;
    private static final int PAGE_SIZE = Config.PAGE_TOTAL;
    private int mNextRequestPage = 1;
    private View notDataView;
    private ShareVideoListAdapter shareVideoListAdapter;
    private int userId;
    private int remoteId;
    private AddTipDialog addTipDialog;
    private String acceptAppCode;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_share;
    }

    @Override
    public void init() {
        super.init();
        mContext = this;
    }

    @Override
    public void initView() {
        super.initView();
        remoteId = getIntent().getIntExtra("remoteId", -1);
        acceptAppCode = getIntent().getStringExtra("acceptAppCode");
        Logger.i("对方id:"+remoteId);
        if (remoteId != -1) {//专家的指导记录
            tvTitle.setText("指导记录");
            userId = remoteId;
        } else {//个人的分享记录
            tvTitle.setText("分享记录");
            userId = PrefUtils.getInt(mContext, PrefUtils.USER_ID, -1);
        }


        notDataView = getLayoutInflater().inflate(R.layout.layout_no_data, (ViewGroup) rvShare.getParent(), false);
        initRefreshLayout();
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        rvShare.setLayoutManager(staggeredGridLayoutManager);
        shareVideoListAdapter = new ShareVideoListAdapter();
        rvShare.setAdapter(shareVideoListAdapter);
        rvShare.addItemDecoration(new SpacesItemDecoration(16, 16));
        shareVideoListAdapter.setOnLoadMoreListener(this,rvShare);
        shareVideoListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ShareVideoBean.ListBean mBean = (ShareVideoBean.ListBean) adapter.getData().get(position);
                if(view.getId()==R.id.fl_delete){
                    if(addTipDialog==null){
                        addTipDialog = new AddTipDialog(mContext);
                    }
                    addTipDialog.setOnClickDialogListener(new AddTipDialog.setOnClickDialogListener() {
                        @Override
                        public void onClickAdd() {
                            cancelShareHttp(mBean.id+"", position);
                        }
                    });
                    addTipDialog.show();
                    addTipDialog.setStr("删除记录", "是否要删除这一条分享记录", "确认删除");
                }
            }
        });
    }

    private void initRefreshLayout() {
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        swipeLayout.setRefreshing(true);
    }

    @Override
    public void initData() {
        refresh();
    }



    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }

    private void refresh() {
        GSYVideoManager.releaseAllVideos();
        mNextRequestPage = 1;
        shareVideoListAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        Map<String, String> map = new HashMap<>();
        map.put("page", mNextRequestPage+"");
        map.put("appCode", acceptAppCode);
        map.put("size", PAGE_SIZE+"");
        if (remoteId != -1) {
            map.put("userId",userId+"");
        }
        ApiService.adminShareList(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<ShareVideoBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        swipeLayout.setRefreshing(true);
                    }

                    @Override
                    public void _onNext(ResponseData<ShareVideoBean> retData) {
                        if (retData.retCode == 10000) {
                            setData(true, retData.data.list,shareVideoListAdapter);
                        } else {
                            ToastUtils.showShort(mContext,retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext,errorMessage);
                        shareVideoListAdapter.setEnableLoadMore(true);
                        swipeLayout.setRefreshing(false);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        shareVideoListAdapter.setEnableLoadMore(true);
                        swipeLayout.setRefreshing(false);
                    }
                });

    }

    private void loadMore() {
        GSYVideoManager.releaseAllVideos();
        Map<String, String> map = new HashMap<>();
        map.put("page", mNextRequestPage+"");
        map.put("size", PAGE_SIZE+"");
        map.put("appCode", acceptAppCode);
        if (remoteId != -1) {
            map.put("userId",userId+"");
        }
        ApiService.adminShareList(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<ShareVideoBean>>() {
                    @Override
                    public void _onNext(ResponseData<ShareVideoBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            boolean isRefresh =mNextRequestPage ==1;
                            setData(isRefresh, retData.data.list,shareVideoListAdapter);
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                        shareVideoListAdapter.loadMoreFail();
                    }
                });
    }

    private void cancelShareHttp(String shareId, int pos) {
        Map<String, String> map = new HashMap<>();
        map.put("shareId", shareId);
        ApiService.cancelShare(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onNext(ResponseData retData) {
                        if (retData != null && retData.retCode == 10000) {
                            ToastUtils.showShort(mContext, "删除成功");
                            shareVideoListAdapter.remove(pos);
                            if(shareVideoListAdapter.getData().size()==0){
                                shareVideoListAdapter.setEmptyView(notDataView);
                            }
                            if(addTipDialog!=null){
                                addTipDialog.dismiss();
                            }
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                    }
                });
    }


    private void setData(boolean isRefresh, List data,BaseQuickAdapter adapter) {

        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            if (size > 0) {
                adapter.setNewData(data);
            } else {
                adapter.setNewData(null);
                adapter.setEmptyView(notDataView);
            }
        } else {
            if (size > 0) {
                adapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            adapter.loadMoreEnd(isRefresh);
        } else {
            adapter.loadMoreComplete();
        }
    }

//    private void createShareHttp() {
//        Map<String, String> map = new HashMap<>();
//        map.put("maintainRecordId", "1");
//        map.put("title", "---");
//        ApiService.createShare(new JSONObject(map).toString())
//                .compose(RxSchedulersHelper.io_main())
//                .subscribe(new RxObserver<ResponseData>() {
//                    @Override
//                    public void _onSubscribe(Disposable d) {
//                        super._onSubscribe(d);
//                    }
//
//                    @Override
//                    public void _onNext(ResponseData responseData) {
//                        if (responseData.retCode == 10000) {
//                            ToastUtils.showShort(mContext, "共享成功");
//                        } else {
//                            ToastUtils.showShort(mContext, responseData.retMsg);
//                        }
//                    }
//
//                    @Override
//                    public void _onError(String errorMessage) {
//                        Log.e("tou", errorMessage);
//                    }
//
//                    @Override
//                    public void onComplete() {
//                        super.onComplete();
//                        srShare.setRefreshing(false);
//                    }
//                });
//    }


    @OnClick(R.id.btn_finish)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        GSYVideoManager.onResume(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
    }


}
